package com.ctsi.commons.util.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * 线程不够,启动新的
 * @author yueming
 *
 */
public class NewThreadRunsPolicy implements RejectedExecutionHandler {
	private static final Logger log = LoggerFactory.getLogger(NewThreadRunsPolicy.class);
	private final boolean daemon;
	public NewThreadRunsPolicy(){
		this(true);
	}
	public NewThreadRunsPolicy(boolean daemon){
		this.daemon=daemon;
	}	
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		try {
			log.info("ThreadPoolExecutor:{} is full ,max :{}",System.identityHashCode(executor),executor.getLargestPoolSize());
			final Thread t = new Thread(r, "Temporary task executor");
			t.setDaemon(daemon);
			t.start();
		} catch (Throwable e) {
			throw new RejectedExecutionException("Failed to start a new thread", e);
		}
	}

}
